/*
 * Copyright (c) 2022-2023 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import fs from "fs"
import path from "path"
import os from "os"
import chalk from "chalk"
import { execCmd } from "../utils.mjs"

const LOCAL_OHPM_PATH = path.join(os.homedir(), ".koala/ohpm")

export async function downloadOhpm(options) {
    const { version } = options

    const packageName = "ohpm"
    const packageVersion = "1.0.0"
    const fileName = `ohpm-${version}.zip`

    if (fs.existsSync(LOCAL_OHPM_PATH))
        fs.rmSync(LOCAL_OHPM_PATH, { recursive: true, force: true })
           
    fs.mkdirSync(LOCAL_OHPM_PATH)

    log(`> Downloading Ohpm ${fileName}...`)
    const { generic_package_archive } = await import("../gitlab/gitlab.mjs")
    await generic_package_archive(
        packageName,
        packageVersion,
        fileName,
        LOCAL_OHPM_PATH,
        null
    )

    process.chdir(path.join(LOCAL_OHPM_PATH, `${packageName}-${version}`))
    await execCmd("npm", ["uninstall", "-g", `@ohos/ohpm`])
    await execCmd("npm", ["i", "-g"])
    const ohpmVersion = await execCmd("ohpm", ["-v"])
    log(`ohpm ${ohpmVersion} has been installed`)

}

export async function listOhpm(options) {
    console.log("not implemented")
}

function log(msg) {
    console.log(chalk.green(msg))
}

function error(msg) {
    console.error(chalk.red(msg))
}